var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var app = getApp();

Page({

	data: {
		dataLoaded: false,
		shopInfo: {}
	},

	onLoad(options) {
		var _self = this;

		_self._shopId = options.shopId;

		app.getUserInfo(function(userInfo) {

			_self.userInfo = userInfo;
			_self._quietLogin();

		});

	},

	_getShop() {
		var _self = this;

		ajax.P('/openapi/User/getQueuePeople', {
			shopId: _self._shopId
		}, function(d) {

			_self.setData({
				dataLoaded: true,
				shopInfo: d.result['shopInfo'],
			});
		});
	},

	_pay(e) {
		var _self = this;
		var params = e.detail.value;

		if (!params.amount) {
			return util.alert('请填写支付金额');
		}

		params.openId = app.getOpenId();

		console.log('--params', params)

		ajax.P('/openapi/User/userBuy', params, function(d) {

			_self._paySuccess(JSON.parse(d.result.wxPayParams));

		});
	},

	/**
	 * 支付成功回调
	 */
	_paySuccess(wxPayParams) {
		wxPayParams.success = function() {
			wx.switchTab({
				url: '/pages/index/index'
			});
		}
		util.wxPay(wxPayParams);
	},

	/**
	 * openid静默登陆
	 */
	_quietLogin: function() {
		var $this = this;

		wx.login({
			success: function(res) {
				ajax.G(
					'/openapi/User/getUserOpenID', {
						jscode: res.code
					},
					function(d) {
						app.setOpenId(d.result.openid);
						$this._openIdLogin(d.result.openid);
					}
				);
			},
			fail: function() {},
			complete: function() {}
		})
	},

	/**
	 * openid静默登陆
	 */
	_openIdLogin: function(openid) {
		var $this = this;
		ajax.P(
			'/openapi/User/login', {
				openId: openid,
				nickName: $this.userInfo.nickName,
				avatarUrl: $this.userInfo.avatarUrl
			},
			function(d) {
				var userSid = d.result.userSid;
				if (userSid) {
					app.setUserSid(userSid);

					$this._getShop();

					// $this._getLocation();
				}
			}
		);
	},

});